package com.example.foo.api.boot;

import java.time.Duration;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.example.support.redis.RedisHelper;

public class TokenHelper {

	public static String createToken(Long userId, Duration expiresIn) {
		String token = userId.toString() + "." + RandomStringUtils.randomAlphanumeric(32) + "." + RandomStringUtils.randomAlphanumeric(8);
		RedisHelper.setex(key(token), expiresIn.getSeconds(), "-");
		return token;
	}

	public static Long verifyToken() {
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String token = request.getHeader(HttpHeaders.AUTHORIZATION);
		if (StringUtils.isBlank(token)) {
			throw new UnauthorizedException("The token must not be null");
		}
		if (!RedisHelper.exists(key(token))) {
			throw new UnauthorizedException("The token does not exist: " + token);
		}
		Long userId = Long.parseLong(token.split("\\.")[0]);
		return userId;
	}

	private static String key(String token) {
		return "token:" + token;
	}

}
